import os
from fastapi import APIRouter,HTTPException,Request
from application.utils import func,aliyunclound
from application import settings
from application.utils.log import getLogger
app = APIRouter()

logger = getLogger(os.environ.get('APP_NAME'))


# @app.get('/api')
# async def api() -> dict:
#     """
#     测试接口
#     :return:
#     """
#     try:
#         print(username)
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=str(e))
#     return {'title': f'{os.environ.get("APP_NAME")}测试接口'}


@app.get('/sms/{mobile}')
async def sms(request: Request, mobile: str) -> dict:
    """
    发送验证码
    @param request: 本次HTTP请求对象
    @param mobile: 要接收验证码的手机
    return
    """
    redis = request.app.state.redis
    code = func.gen_int(5)
    timer = 10 * 60
    ret = await redis.setex(f"sms_{mobile}", timer, code)
    if ret:
        # 发送短信
        # 发送短信
        aliyun = aliyunclound.AliYunClound(settings.ALIYUN['key'], settings.ALIYUN['secret'])
        data = {
            'code': code
        }
        result = await aliyun.sms_async(mobile, data, settings.ALIYUN['sms']['sign_name'],
                                        settings.ALIYUN['sms']['template_code'])

        if result.code != 'OK':
            logger.error(f'短信发送失败！{result.message}')
            raise HTTPException(status_code=500, detail='短信发送失败！')

        return {
            'code': 200,
            'err_msg': '短信已发送，请留意手机',
            'status': 'Success',
        }
    return {'mobile': mobile, 'sms_code': code}